import datetime
import logging
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import REDIRECT_FIELD_NAME


class APIRequestLoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.logger = logging.getLogger('api_logger')

    def __call__(self, request):
        # 请求开始时记录日志
        try:
            response = self.get_response(request)
            self.logger.info(str(request.user.username) + '  ' + str(
                request.user.username) + f"    API Request: {request.method} {request.path} - Started")
            # 响应返回时记录日志，可以包含响应状态码等信息 包含访问时间""
            #获取当前时间以字符串

            self.logger.info(
                str(request.user.username) + '  ' +
                str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                + f""
                  f"    API Request: {request.method} {request.path} - Ended with status" f"code {response.status_code}")
        except Exception as e:
            response = self.get_response(request)
            self.logger.error(
                str(request.user.username) + '  ' + str(
                    request.user.username) + f"    API Request: {request.method} {request.path} - Error: {str(e)}")

        return response
